$(document).ready(function () {
    // 绑定事件
    bindEvents();
    // 获取订单列表并显示
    getOrderList(fillOrders);

    function bindEvents() {
        $('.afc-create-order-btn').on('click', handleCreateOrderBtnClick);
        $('.afc-create-order-form .form-control').on('focus', function () {
            $('.asf-form-validation-msg').hide();
        });
    }

    function handleCreateOrderBtnClick() {
        const formData = $('.afc-create-order-form').serializeArray();
        let data = {};
        let valid = true;
        formData.map(function (item) {
            if (!item.value) {
                valid = false;
            } else {
                data[item.name] = item.value;
            }
        });
        if (valid) {
            createOrder(data, function () {
                getOrderList(fillOrders);
                $('#createOrderModal').modal('hide');
            })
        } else {
            $('.asf-form-validation-msg').html('Your input was invalid, please check...');
            $('.asf-form-validation-msg').show();
        }
    }

    function handleRepayOrderActionClick(event) {
        const data = $(event.currentTarget).data();
        const orderNo = data.orderNo;
        repay(orderNo, function () {
            getOrderList(fillOrders);
        });
    }

    function fillOrders(data) {
        if (data) {
            let tableContent = '';
            data.map(function (order, index) {
                if (index < 10) {
                    const status = order.status === 'DONE' ? 'success' : 'danger';
                    const action = order.status === 'DONE' ? '' : '<span class="afc-order-action-repay badge badge-info" data-order-no="' + order.orderNo + '">支付</span>';
                    const statusHtml = '<span class="badge badge-' + status + '">' + order.status + '</span>';
                    tableContent += '<tr>'
                    tableContent += '<td>' + order.orderNo + '</td>';
                    tableContent += '<td>' + new Date(order.gmtCreate).toLocaleString() + '</td>';
                    tableContent += '<td>' + order.payAmount + '</td>';
                    tableContent += '<td>' + statusHtml + '</td>';
                    tableContent += '<td>' + order.buyerId + '</td>';
                    tableContent += '<td>' + order.sellerId + '</td>';
                    tableContent += '<td>' + action + '</td>';
                    tableContent += '</tr>'
                }

            });
            $('.afc-orders-body').html(tableContent);

            $('.afc-order-action-repay').on('click', handleRepayOrderActionClick);
        }
    }


});